package com.dayaokeji.rhythmschoolstudent.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;

import com.dayaokeji.imkitwrapper.init.ImKitWrapper;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.App;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.StudentIdLoginActivity;
import com.dayaokeji.rhythmschoolstudent.databases.dao.UserInfoDao;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.ServerResponseCode;
import com.orhanobut.logger.Logger;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Gorden on 2017/9/23.
 */

public abstract class ServerCallback<T> implements Callback<ServerResponse<T>>, DialogInterface.OnCancelListener {

    private ProgressDialog progressDialog;
    private boolean isShowNetworkError = true;

    public static boolean loginNavigation = false;
    private Context context;

    public ServerCallback() {
        this(null, null);
    }

    public ServerCallback(Context context, String message) {
        this(context, message, false);
    }

    public ServerCallback(Context context, String message, boolean cancelable) {
        if (context != null) {
            this.context = context;
            progressDialog = ProgressDialog.show(context, "提示", message == null ? "请稍后..." : message);
            if (cancelable) {
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.setCancelable(false);
                progressDialog.setOnCancelListener(this);
            }
        }
    }


    @Override
    public void onResponse(Call<ServerResponse<T>> call, Response<ServerResponse<T>> response) {
        cancelDialog();
        if (response.isSuccessful()) {
            ServerResponse<T> body = response.body();
            if (body  != null && body.getHeader() != null) {
                int code = body.getHeader().getCode();
                boolean success = code == ServerResponseCode.SUCCESS;
                if (!success) {
                    switch (code) {
                        // 其他状态处理，如token过期等
                        case ServerResponseCode.SYSTEM_ERROR:
                            if (showNetworkError()) {
                                ToastUtils.warning(body.getHeader().getMessage());
                            }
                            break;
                        case ServerResponseCode.INVALID_TOKEN:
                            UserUtils.setAccessToken(null);
                            UserUtils.setUserInfo(null);
                            UserInfoDao.delUserInfo();
                            ImKitWrapper.stopImService();
                            JPushInterface.setAlias(App.getAppContext(), "", null);
                            UserUtils.stopService(App.getAppContext());
                            if (App.getAppContext() != null) {
                                if (!loginNavigation) {
                                    ActivityStackManager.finishAll();
                                    Intent intent = new Intent(App.getAppContext(), StudentIdLoginActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    App.getAppContext().startActivity(intent);
                                    loginNavigation = true;
                                }
                            }
                            break;
                        case ServerResponseCode.NON_DATA:
                            // TODO: 2018/3/20 没有数据
                            break;
                        case ServerResponseCode.REPEAT_REQ:
                            // TODO: 2018/3/24 重复提交
                            break;
                        default: {
                            try{
                                String msg = TextUtils.isEmpty(body.getHeader().getMessage()) ? "操作失败，错误码："+body.getHeader().getCode() : body.getHeader().getMessage();
                                ToastUtils.info(msg);
                            }catch (Exception e){
                                e.printStackTrace();
                                onFailure(call,new StatusException(response.code(),"解析返回值失败"));
                            }
                            break;
                        }
                    }
                }
                onResponse(success, body);
            }

        } else {
            String message = response.message();
            if (response.code() == 500) {
                try {
                    message = "error = " + response.errorBody().string();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            onFailure(call, new StatusException(response.code(), message));
        }
    }

    @Override
    public void onFailure(Call<ServerResponse<T>> call, Throwable t) {
        cancelDialog();
        if (call.isCanceled()) {
            return;
        }
        try {
            Logger.e("请求接口失败" + call.request().url(), t.getMessage());
            if (showNetworkError()) {
                ToastUtils.warning("网络请求失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public abstract void onResponse(boolean success, ServerResponse<T> response);


    protected boolean showNetworkError() {
        return isShowNetworkError;
    }

    public void setShowNetworkError(boolean showNetworkError) {
        isShowNetworkError = showNetworkError;
    }

    @Override
    public void onCancel(DialogInterface dialogInterface) {
        cancelDialog();
    }

    private void cancelDialog() {
        if (context != null) {
            if (context instanceof Activity) {
                if (!((Activity) context).isFinishing()) {
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                        progressDialog = null;
                    }
                }
            }
        }
    }


    /**
     * 请求失败异常
     */
    private static class StatusException extends RuntimeException {

        private int responseCode;
        private String responseMessage;

        public StatusException(int responseCode, String responseMessage) {
            this("响应 ： " + responseCode + "  " + responseMessage, responseCode, responseMessage);
        }

        public StatusException(String message, int responseCode, String responseMessage) {
            super(message);
            this.responseCode = responseCode;
            this.responseMessage = responseMessage;
        }

        public int getResponseCode() {
            return responseCode;
        }

        public String getResponseMessage() {
            return responseMessage;
        }
    }
}
